﻿namespace Leo.MSATracert
{
    public static class ServiceInvocationLinkTrace
    {
        private static readonly AsyncLocal<LinkTracertPrincipal> principal = new AsyncLocal<LinkTracertPrincipal>();
        public static LinkTracertPrincipal GetPrincipal(string traceId = null, IEnumerable<IApiToken> tokens = null)
        {
            if (ServiceInvocationLinkTrace.principal.Value == null)
            {
                if (string.IsNullOrEmpty(traceId))
                {
                    traceId = Guid.NewGuid().ToString("N").ToLower();
                }
                ServiceInvocationLinkTrace.principal.Value = new LinkTracertPrincipal(traceId, tokens);
            }
            if (!string.IsNullOrEmpty(traceId) && ServiceInvocationLinkTrace.principal.Value.RequestId != traceId)
            {
                ServiceInvocationLinkTrace.principal.Value.RequestId = traceId;
            }
            return ServiceInvocationLinkTrace.principal.Value;
        }
         
        public static void SetPrincipal(string traceId, IEnumerable<IApiToken> tokens)
        {
            ServiceInvocationLinkTrace.GetPrincipal(traceId, tokens);
        } 
    }
}
